//
//  CHJCaptureManager.m
//  CHJVideoKit_Example
//
//  Created by jiaxuzhou on 2017/12/2.
//  Copyright © 2017年 jxzjxz. All rights reserved.
//

#import "CHJCaptureManager.h"
#import "YXVideoUtil.h"
#import "YXCamera.h"
#import <CommonCrypto/CommonDigest.h>
#import "SenseAr.h"
#import "CHJCaptureDataSource.h"
#import "YXVideoComponentVideo.h"
#import "UIDevice+Hardware.h"

@interface CHJCaptureManager ()
<
YXCameraDelegate
>
{
    YXCamera *camera;
    SenseArMaterialService *service;
    SenseArMaterialRender *renderer;
    SenseArMobilePhoneClient  *mobilePhone;
    SenseArMaterial *materialCurrent;
    GLuint _textureBeautifyOut, _textureStickerOut, _textureFilterOut;
    GLuint _iImageWidth, _iImageHeight;
    
    NSString *currentPreset;
    
    NSString *appIDKey;
    NSString *aRKey;
    BOOL isLowDevice;
    BOOL isValidSenseAr;
}

@property (nonatomic, strong) NSMutableArray *videoArr;
@property (nonatomic, assign) CGFloat vidDuration;

@property (nonatomic, assign) TeXiao_Type texiaoType;

@end


@implementation CHJCaptureManager

#pragma mark -- ***********************Necessary method**********************************************

- (void)updateCapturePreset:(NSString *)preset
{
    currentPreset = preset;
    [camera updateCapturePreset:currentPreset];
}

- (void)setCaptureType:(CHJCameraCaptureType)captureType
{
    _captureType = captureType;
    
    /// 分辨率是否为1280 ＊720
    BOOL is720 = !isLowDevice;
    
    if (_captureType == CHJCameraCaptureType_FullScreen)
    {
        [camera updateCaptureVideoSize:is720 ? CGSizeMake(720, 1280) : CGSizeMake(480, 640)];
        
    } else if (_captureType == CHJCameraCaptureType_Square)
    {
        [camera updateCaptureVideoSize:is720 ? CGSizeMake(720, 720) : CGSizeMake(480, 480)];
    }
    else if (_captureType == CHJCameraCaptureType_ZhaiPing)
    {
        [camera updateCaptureVideoSize:is720 ? CGSizeMake(540, 304) : CGSizeMake(480, 270)];
    }
    else if (_captureType == CHJCameraCaptureType_4_5)
    {
        [camera updateCaptureVideoSize:is720 ? CGSizeMake(720, 900) : CGSizeMake(480, 600)];
    }
}

- (void)setPreviewFrame:(CGRect)previewFrame
{
    _previewFrame = previewFrame;
    [camera runSyncInSessionQueue:^{
        camera.previewView.frame = previewFrame;
    }];
}

/**
 初始化配置
 */
- (void)setupWithAppId:(NSString *)appId arId:(NSString *)arId
{
    appIDKey = appId;
    aRKey = arId;
    
    NSString *deviceName = [[UIDevice alloc] hardwareDescription];//获取机型
    BOOL is_low_5_seriers = ([deviceName isEqualToString:@"iPhone 5c (GSM)"] ||
                             [deviceName isEqualToString:@"iPhone 5c (Global)"] ||
                             [deviceName isEqualToString:@"iPhone 5 (GSM)"] ||
                             [deviceName isEqualToString:@"iPhone 5 (Global)"] ||
                             [deviceName isEqualToString:@"iPhone 4 (GSM Rev A)"] ||
                             [deviceName isEqualToString:@"iPhone 4 (CDMA)"] ||
                             [deviceName isEqualToString:@"iPhone 4S"]
                             );
    bool is_lowdevice = [UIScreen mainScreen].bounds.size.height <= 568;
    
    isLowDevice = is_lowdevice && is_low_5_seriers;
    
    self.videoArr = [NSMutableArray arrayWithCapacity:0];
    [[CHJCaptureDataSource shareDataSource] setVideoClips:self.videoArr];
    [self setupCamera];
    isValidSenseAr = [self checkActiveCode];
    if ([self.delegate respondsToSelector:@selector(chj_fullscreen_camera_getNetWorking)])
    {
        isValidSenseAr = [self.delegate chj_fullscreen_camera_getNetWorking];
    }
    [self SenseARRenderer];
    [self req_material];
}

- (void)setupCamera
{
    camera = [YXCamera new];
    [self updateCapturePreset:YXCameraCapturePreset1280x720];
    [self setCaptureType:_captureType];
    [camera setCameraPosition:(AVCaptureDevicePositionFront)];
    camera.previewView.frame = _previewFrame;
    [camera setDelegate:self];
    
}

-  (void)changeCameraToPhoto
{
    if (isLowDevice)
    {
        [self updateCapturePreset:YXCameraCapturePreset640x480];
    }
    else
    {
        [self updateCapturePreset:YXCameraCapturePreset1920x1080];
    }
    
    [self setCaptureType:_captureType];

}
-  (void)changeCameraToVideo
{
    if (isLowDevice)
    {
        [self updateCapturePreset:YXCameraCapturePreset640x480];
    }
    else
    {
        [self updateCapturePreset:YXCameraCapturePreset1280x720];
    }
    
    [self setCaptureType:_captureType];
}

- (void)registRecorder
{
    
}

- (void)destoryRecorder
{
    [self destoryTempTextures];
    [renderer releaseGLResource];
}

/**
 开启取景器 在viewDidAppear中
 */
- (void)startPreview
{
    [camera startSampling];
}

/**
 关闭取景器 在ViewDidDisappear中
 */
- (void)stopPreview
{
    [camera stopSampling];
}

/**
 开始拍摄
 */
- (void)startCapture
{
    [camera begineSegment];
}

/**
 结束拍摄
 */
- (void)endCapture
{
    [camera endSegment];
}

#pragma mark -- ***********************Setting method**********************************************

/**
 切换摄像头（前置，后置）
 */
- (void)switchCamera
{
    camera.cameraPosition = camera.cameraPosition == AVCaptureDevicePositionBack ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;
    
    [self fullscreen_camera_changed_device_position:camera.cameraPosition == AVCaptureDevicePositionBack ? NO : YES];
}

/**
 开启闪光灯
 @param isOn YES 开启。NO 关闭  默认关闭状态
 */
- (void)enableFlash:(BOOL)isOn
{
    [camera enableFlash:isOn];
}

/**
 回删所有拍摄的视频片段
 */
- (void)removeAllClips
{
    [camera removeAllSegments];

    [camera runSyncInSessionQueue:^{
        
        for (YXVideoComponentVideo *video in self.videoArr) {
            unlink(video.originalFilePath.UTF8String);
        }
        
        [self.videoArr removeAllObjects];
        
    }];
    

}

/**
 回删最后一次拍摄的视频片段
 */
- (void)removeLastVideoClip
{
    [camera removeLastSegment];
    [camera runSyncInSessionQueue:^{
        
        YXVideoComponentVideo *video = [self.videoArr lastObject];
        unlink(video.originalFilePath.UTF8String);
        [self.videoArr removeLastObject];
    }];
    
}


/**
 对焦
 @param point 焦点
 */
- (void)startFocus:(CGPoint)point
{
    [camera focusAt:point];
    
    [self fullscreen_camera_did_stop_focus];
}

#pragma mark -- ***********************get message method**********************************************

/**
 获取视频片段数
 */
- (NSInteger)getCaptureClipsCount
{
    return self.videoArr.count;
}

/**
 获取录制视频的时长
 */
- (CGFloat)getCapturedDuration
{
    return _vidDuration;
}

- (UIView *)getPreview
{
    return camera.previewView;
}

/**
 是否正在录制
 @return YES。NO
 */
- (BOOL)getIsRecordingVideo
{
    return [camera isRecording];
}

/**
 获取当前拍摄图片
 */
- (void)getCaptureImage:(void(^ __nonnull)(UIImage *__nullable image))finish;
{
    
    
    [camera prepareCaptureProcessedImage];
    [camera captureProcessedImage:^(UIImage *outputImage)
     {
         NSLog(@"%@", outputImage);
         dispatch_async(dispatch_get_main_queue(), ^{

         if (finish)
         {
             finish(outputImage);
         }
         });
         
         [camera endCaptureProcessedImage];
     }];
}

- (SenseArMaterial *)getcrtMtr
{
    return materialCurrent;
}

- (SenseArRenderStatus)useMaterial:(SenseArMaterial *)material
{
    SenseArMaterialAction *action = [material.arrMaterialTriggerActions firstObject];

    if (action.iTriggerAction == MOUTH_AH   ||
        action.iTriggerAction == EYE_BLINK  ||
        action.iTriggerAction == HEAD_PITCH ||
        action.iTriggerAction == BROW_JUMP  ||
        action.iTriggerAction == HEAD_YAW   ||
        action == nil)
    {
        self.texiaoType = TeXiao_Type_Face;
    }
    else
    {
        self.texiaoType = TeXiao_Type_Hand;
    }
    
    materialCurrent = material;
   SenseArRenderStatus status = [renderer setMaterial:material];
    return status;
}

- (void)setPreviewHeight:(CGFloat)height
{
    [camera runSyncInSessionQueue:^{
        CGRect frame = camera.previewView.frame;
        frame.size.height = height;
        camera.previewView.frame = frame;
        
    }];
}

- (void)capturePhoto:(void(^ __nonnull)(NSError *__nullable error, UIImage *__nullable image))completionHandler
{
    [camera prepareCaptureProcessedImage];
//    if (isValidSenseAr)
    {
        [camera captureProcessedImage:^(UIImage *outputImage)
         {
             NSLog(@"%@", outputImage);
             if (outputImage)
             {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if (completionHandler)
                     {
                         completionHandler(nil,outputImage);
                     }
                 });
             }
             
             [camera endCaptureProcessedImage];
         }];
    }
//    else
//    {
//        [camera captureStillImage:^(UIImage *outputImage)
//         {
//             NSLog(@"%@", outputImage);
//             if (outputImage)
//             {
//                 dispatch_async(dispatch_get_main_queue(), ^{
//                     if (completionHandler)
//                     {
//                         completionHandler(nil,outputImage);
//                     }
//                 });
//             }
//
//
//             [camera endCaptureProcessedImage];
//         }];
//    }
}



#pragma mark -- *********************** MPTFullScreenCameraDelegate  ***********************

/**
 视频采样数据回调
 
 @param camera camera实例
 @param videoSampleBuffer 视频采样数据
 @param pixelBuffer 待赋值的处理后的视频数据 buffer指针 可选,如果不选,则修改后的数据不会被写入文件
 @param texture 待赋值的处理后的纹理指针 可选,如果不选,则再次上传 buffer 有显示要求则用于显示
 */
- (void)camera:(YXCamera *)camera didOutputVideoSampleBuffer:(CMSampleBufferRef)videoSampleBuffer insteadPixelBuffer:(CVPixelBufferRef *)spixelBuffer insteadTexture:(GLuint *)stexture
{
    YXUploadTexture(CMSampleBufferGetImageBuffer(videoSampleBuffer), ^(GLuint texture, CGSize size)
                    {
                        GLuint textureReslut = 0;
                        __block Byte *pFrameInfo = (Byte *)malloc(sizeof(Byte) * 10000);
                        memset(pFrameInfo, 0, 10000 * sizeof(Byte));
                        
                        int iInfoLength = sizeof(Byte) * 10000;
                        
                        [self createTmpTextureWithSize:size];
                        
                        SenseArRenderStatus iRenderStatus = RENDER_UNKNOWN;
                        
                        SenseArDetectResult *detectResult = [[SenseArDetectResult alloc] init];
                        
                        CVPixelBufferRef imageBuffer = CMSampleBufferGetImageBuffer(videoSampleBuffer);
                        
                        CVPixelBufferLockBaseAddress(imageBuffer, 0);
                        unsigned char * pBGRAImageInput = CVPixelBufferGetBaseAddress(imageBuffer);
                        CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
                        
                        if (!isValidSenseAr)
                        {
                            free(pFrameInfo);
                            return ;
                        }
                        
                        if ([self.delegate respondsToSelector:@selector(chj_fullscreen_camera_getNetWorking)])
                        {
                            BOOL hasNet = [self.delegate chj_fullscreen_camera_getNetWorking];
                            
                            if (!hasNet)
                            {
                                free(pFrameInfo);
                                return;
                            }
                        }
                        
                        [renderer setFrameWidth:size.width height:size.height stride:(int)CVPixelBufferGetBytesPerRow(imageBuffer)];
                        
                        /// 获取手机方向
                        SenseArRotateType iRotate = [self getRotateTypeWithDeviceOrientation];
                        
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
                        iRenderStatus = [renderer beautifyAndGenerateFrameInfo:pFrameInfo
                                                               frameInfoLength:&iInfoLength
                                                             withPixelFormatIn:PIX_FMT_BGRA8888
                                                                       imageIn:pBGRAImageInput
                                                                     textureIn:texture
                                                                    rotateType:iRotate
                                                                needsMirroring:0
                                                                pixelFormatOut:(PIX_FMT_BGRA8888)
                                                                      imageOut:0
                                                                    textureOut:_textureBeautifyOut
                                                                  detectResult:detectResult];
#pragma clang diagnostic pop
                        textureReslut = _textureBeautifyOut;
                        
                        
                        
                        SenseArFrameActionInfo *currentFrameActionInfo = nil;
                        
                        currentFrameActionInfo = [renderer getCurrentFrameActionInfo];
                        
                        
                        iRenderStatus = [renderer renderMaterialWithFrameInfo:pFrameInfo
                                                              frameInfoLength:iInfoLength
                                                                    textureIn:textureReslut
                                                                   textureOut:_textureStickerOut
                                                                  pixelFormat:PIX_FMT_BGRA8888
                                                                     imageOut:0];
                        
                        
                        *stexture = _textureStickerOut;
                        
                        free(pFrameInfo);
                        
                        
                        if (iRenderStatus == RENDER_SUCCESS) {
                            SenseArFrameActionInfo *frameActionInfo = [renderer getCurrentFrameActionInfo];
                            
                            
                            /// 脸
                            if (materialCurrent)
                            {
                                if (self.texiaoType == TeXiao_Type_Face)
                                {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [self fullscreen_camera_detected_face:frameActionInfo.arrFaces.count];
                                    });
                                }
                                else
                                {
                                    /// 手 +表情
                                    dispatch_async(dispatch_get_main_queue(), ^{
                             
                                        [self fullscreen_camera_detected_hand:(frameActionInfo.arrHands.count)];
                                    });
                                }
                            }
                        
                        } else {
                            //            NSLog(@"sense render status failed");
                        }
                        
                    });
}

/**
 拍摄时间回调  时时 更新UI时间
 @param duration 时长
 */

- (void)camera:(YXCamera *)camera didRecordedVideoSegmentDuration:(CMTime)duration
{
    _vidDuration = CMTimeGetSeconds(duration);
    if ([self.delegate respondsToSelector:@selector(chj_fullscreen_camera_captured_duration:)])
    {
        [self.delegate chj_fullscreen_camera_captured_duration:CMTimeGetSeconds(duration)];
    }
}


/**
 每有一段视频掉一次 每拍摄一段视频处理完成回调
 @param error 错误信息
 */
- (void)camera:(YXCamera *)camera didRecordedVideoSegment:(YXVideoSegment *)videoSegment error:(NSError *)error;
{
    
    if (!error)
    {
    YXVideoComponentVideo *video = [YXVideoComponentVideo assetWithURL:[NSURL fileURLWithPath:videoSegment.filePath]];
        [self.videoArr addObject:video];
    }
    
    if ([self.delegate respondsToSelector:@selector(chj_fullscreen_camera_captured_video:)])
    {
        [self.delegate chj_fullscreen_camera_captured_video:error];
    }
}

- (void)camera:(YXCamera *)camera sessionPrepared:(BOOL)isPrepared
{
    if ([self.delegate respondsToSelector:@selector(chj_fullscreen_camera_initSessionPrepared:)])
    {
        [self.delegate chj_fullscreen_camera_initSessionPrepared:isPrepared];
    }
}

#pragma mark -- 调用对外的代理方法

/**
 对焦完成回调
 */
- (void)fullscreen_camera_did_stop_focus
{
    if ([self.delegate respondsToSelector:@selector(chj_fullscreen_camera_did_stop_focus)])
    {
        [self.delegate chj_fullscreen_camera_did_stop_focus];
    }
}

/**
 切换摄像头后的摄像头位置 更新UI
 
 @param is_front 是否是前置 YES 前置， NO 后置
 */
- (void)fullscreen_camera_changed_device_position:(BOOL)is_front
{
    if ([self.delegate respondsToSelector:@selector(chj_fullscreen_camera_changed_device_position:)])
    {
        [self.delegate chj_fullscreen_camera_changed_device_position:is_front];
    }
}

- (void)fullscreen_camera_detected_face:(BOOL)face_result
{
    if ([self.delegate respondsToSelector:@selector(chj_fullscreen_camera_detected_face:)])
    {
        [self.delegate chj_fullscreen_camera_detected_face:face_result];
    }
}


- (void)fullscreen_camera_detected_hand:(BOOL)hand_result
{
    if ([self.delegate respondsToSelector:@selector(chj_fullscreen_camera_detected_hand:)])
    {
        [self.delegate chj_fullscreen_camera_detected_hand:hand_result];
    }
}



- (BOOL)checkActiveCode
{
    NSString *strLicensePath = [[NSBundle mainBundle] pathForResource:@"SENSEME" ofType:@"lic"];
    NSData *dataLicense = [NSData dataWithContentsOfFile:strLicensePath];
    
    NSString *strKeySHA1 = @"SENSEME";
    NSString *strKeyActiveCode = @"ACTIVE_CODE";
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *strStoredSHA1 = [userDefaults objectForKey:strKeySHA1];
    NSString *strLicenseSHA1 = [self getSHA1StringWithData:dataLicense];
    
    NSString *strActiveCode = nil;
    
    NSError *error = nil;
    BOOL bSuccess = NO;
    
    if (strStoredSHA1.length > 0 && [strLicenseSHA1 isEqualToString:strStoredSHA1]) {
        
        // Get current active code
        // In this app active code was stored in NSUserDefaults
        // It also can be stored in other places
        strActiveCode = [userDefaults objectForKey:strKeyActiveCode];
        
        // Check if current active code is available
#if CHECK_LICENSE_WITH_PATH
        
        // use file
        bSuccess = [SenseArMaterialService checkActiveCode:strActiveCode licensePath:strLicensePath error:&error];
#else
        
        // use buffer
        NSData *licenseData = [NSData dataWithContentsOfFile:strLicensePath];
        
        bSuccess = [SenseArMaterialService checkActiveCode:strActiveCode
                                               licenseData:licenseData
                                                     error:&error];
        
#endif
        
        if (bSuccess && !error) {
            
            // check success
            return YES;
        }
    }
    
    /*
     1. check fail
     2. new one
     3. update
     */
    
    
    // generate one
#if CHECK_LICENSE_WITH_PATH
    
    // use file
    strActiveCode = [SenseArMaterialService generateActiveCodeWithLicensePath:strLicensePath
                                                                        error:&error];
    
#else
    
    // use buffer
    strActiveCode = [SenseArMaterialService generateActiveCodeWithLicenseData:dataLicense
                                                                        error:&error];
#endif
    
    if (!strActiveCode.length && error) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误提示" message:@"使用 license 文件生成激活码时失败，可能是授权文件过期。" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        
        [alert show];
        
        return NO;
        
    } else {
        
        // Store active code
        
        [userDefaults setObject:strActiveCode forKey:strKeyActiveCode];
        [userDefaults setObject:strLicenseSHA1 forKey:strKeySHA1];
        
        [userDefaults synchronize];
    }
    
    return YES;
}

- (void)SenseARRenderer
{
    // 根据实际需求决定是否开启美颜和动作检测
    NSString *strModelPath = [[NSBundle mainBundle] pathForResource:@"M_SenseAR_1.3.0"
                                                             ofType:@"model"];
    extern void * YXGetDefaultGLContext(void);
    
    renderer =
    [SenseArMaterialRender instanceWithModelPath:strModelPath
                                          config:SENSEAR_ENABLE_HUMAN_ACTION |SENSEAR_ENABLE_BEAUTIFY
                                         context:(__bridge EAGLContext *)YXGetDefaultGLContext()];
    [renderer initGLResource];
}

- (void)req_material
{
    __weak typeof(self) weakself = self;

    service = [SenseArMaterialService sharedInstance];
    _serviceR = service;
    [service authorizeWithAppID:appIDKey
                         appKey:aRKey
                      onSuccess:^
     {
         NSLog(@"%s", __func__);
         {
             NSLog(@"%s", __func__);
             SenseArClient *client = (SenseArClient*)[[SenseArShortVideoClient alloc] init];
             client.strID = @"userId";
             SenseArConfigStatus iStatus = [weakself.serviceR configureClientWithType:(SmallVideo) client:client];
             
             if (iStatus == CONFIG_OK)
             {
                 
                 // 设置缓存大小 , 默认为120M
                 [service setMaxCacheSize:120000000];
                 
                 /*
                 [service fetchMaterialsWithUserID:@"415465"
                                           GroupID:@"38a478708d3711e7a7f100163e0e6edd"
                                         onSuccess:^(NSArray<SenseArMaterial *> *arrMaterials)
                  {
                      SenseArMaterial *material = [arrMaterials lastObject];
                      if (![service isMaterialDownloaded:material])
                      {
                          [service downloadMaterial:material
                                          onSuccess:^(SenseArMaterial *material)
                           {
                               [renderer setMaterial:material];
                           }
                                          onFailure:^(SenseArMaterial *material, int iErrorCode, NSString *strMessage)
                           {
                               
                           }
                                         onProgress:^(SenseArMaterial *material, float fProgress, int64_t iSize)
                           {
                               NSLog(@"%.2f", fProgress);
                           }];
                      }
                      else
                      {
                          [renderer setMaterial:material];
                      }
                  }
                                         onFailure:^(int iErrorCode, NSString *strMessage)
                  {
                      
                  }];
                  */
             }
             else
             {
                 
                 dispatch_async(dispatch_get_main_queue(), ^{
                     
                     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"服务配置失败" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
                     
                     [alert show];
                 });
             }
         }
     }
                      onFailure:^(SenseArAuthorizeError iErrorCode)
     {
         NSLog(@"%s", __func__);
     }];
}


- (NSString *)getSHA1StringWithData:(NSData *)data
{
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *strSHA1 = [NSMutableString string];
    
    for (int i = 0 ; i < CC_SHA1_DIGEST_LENGTH ; i ++) {
        
        [strSHA1 appendFormat:@"%02x" , digest[i]];
    }
    
    return strSHA1;
}

- (void)destoryTempTextures
{
    glDeleteTextures(1, &_textureBeautifyOut);
    glDeleteTextures(1, &_textureStickerOut);
    glDeleteTextures(1, &_textureFilterOut);
}


void activeAndBindTexture(GLenum textureActive,
                          GLuint *textureBind,
                          Byte *sourceImage,
                          GLenum sourceFormat,
                          GLsizei iWidth,
                          GLsizei iHeight)
{
    glActiveTexture(textureActive);
    glBindTexture(GL_TEXTURE_2D, *textureBind);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, iWidth, iHeight, 0, sourceFormat, GL_UNSIGNED_BYTE, sourceImage);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glBindTexture(GL_TEXTURE_2D, 0);
}

- (void)createTmpTextureWithSize:(CGSize)size
{
    if (_iImageWidth != size.width || _iImageHeight != size.height)
    {
        [self destoryTempTextures];
        
        _iImageWidth = size.width;
        _iImageHeight = size.height;
        
        if (_iImageHeight * _iImageWidth)
        {
            // 创建美颜和贴纸的结果纹理
            glGenTextures(1, &_textureBeautifyOut);
            activeAndBindTexture(GL_TEXTURE1, &_textureBeautifyOut, NULL, GL_RGBA, _iImageWidth, _iImageHeight);
            
            glGenTextures(1, &_textureStickerOut);
            activeAndBindTexture(GL_TEXTURE2, &_textureStickerOut, NULL, GL_RGBA, _iImageWidth, _iImageHeight);
            //创建滤镜纹理
            glGenTextures(1, &_textureFilterOut);
            activeAndBindTexture(GL_TEXTURE3, &_textureFilterOut, NULL, GL_RGBA, _iImageWidth, _iImageHeight);
        }
    }
}

/// 获取方向
- (SenseArRotateType)getRotateTypeWithDeviceOrientation
{
    UIDeviceOrientation iDeviceOrientation = [[UIDevice currentDevice] orientation];
    
    SenseArRotateType iRotate;
    
    switch (iDeviceOrientation) {
            
        case UIDeviceOrientationPortrait:
            
            iRotate = CLOCKWISE_ROTATE_0;
            break;
            
        case UIDeviceOrientationPortraitUpsideDown:
            
            iRotate = CLOCKWISE_ROTATE_180;
            break;
            
        case UIDeviceOrientationLandscapeLeft:
            
            iRotate = CLOCKWISE_ROTATE_270;
            
            break;
            
        case UIDeviceOrientationLandscapeRight:
            
            iRotate = CLOCKWISE_ROTATE_90;
            
            break;
            
        default:
            
            iRotate = CLOCKWISE_ROTATE_0;
            break;
    }
    
    return iRotate;
}

- (void)enableRandomMaterial {
    NSArray *materialParts = renderer.getMaterialParts;
    
    ///所有分主后的素材
    NSMutableDictionary *mdict = [NSMutableDictionary dictionary];
    NSInteger intTemp = SENSEAR_EYE_BLINK+SENSEAR_MOUTH_AH +SENSEAR_HEAD_YAW+SENSEAR_HEAD_PITCH+SENSEAR_BROW_JUMP+SENSEAR_HAND_GOOD+SENSEAR_HAND_PALM+SENSEAR_HAND_LOVE+SENSEAR_HAND_HOLDUP+SENSEAR_HAND_CONGRATULATE;
    for (SenseArMaterialPart *part in materialParts)
    {
        if ((part.iTriggerType &intTemp)>0)
        {
            NSString *strName = part.strPartName;
            if (strName)
            {
                NSString *strKey = [strName substringToIndex:1];
                if (!mdict[strKey])
                {
                    NSMutableArray *mary = [NSMutableArray array];
                    [mary addObject:part];
                    [mdict setValue:mary forKey:strKey];
                }
                else
                {
                    NSMutableArray *mary = [NSMutableArray arrayWithArray:mdict[strKey]];
                    [mary addObject:part];
                    [mdict setValue:mary forKey:strKey];
                }
            }
        }
    }
    
    NSMutableArray *noneFaceParts = [NSMutableArray arrayWithArray:[mdict allKeys]];
    ///  分组大于1时才随机
    bool isNeedEnable = noneFaceParts.count > 1;
    
    if (isNeedEnable)
    {
        /// 获取随机数
        NSInteger seed = [self genSeed:noneFaceParts];
        /// 移除随机数
        [noneFaceParts removeObjectAtIndex:seed];
        
        NSMutableArray *maryClose = [NSMutableArray array];
        for (NSInteger i = 0; i < noneFaceParts.count; i++)
        {
            [maryClose addObjectsFromArray:mdict[noneFaceParts[i]]];
        }
        
        for (NSInteger i = 0; i < maryClose.count; i++)
        {
            SenseArMaterialPart *part = maryClose[i];
            [part setIsEnable:NO];
        }
        
        [renderer enableMaterialParts:materialParts];
    }
}

- (NSInteger)genSeed:(NSArray *)nonFaceArr
{
    static int seed = -1;
    if ( materialCurrent== nil || nonFaceArr == nil) {
        seed = -1;
    }
    if (seed == -1 && materialCurrent && nonFaceArr.count) {
        seed = arc4random() % nonFaceArr.count;
    }
    return seed;
}





@end
